package com.yogee.topseller.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.NetUtil;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.base.HttpActivity;
import com.yogee.topseller.adapter.JigouAdapter;
import com.yogee.topseller.bean.JigouBean;
import com.yogee.topseller.fragment.GongsiProFragment;
import com.yogee.topseller.fragment.zhoubian.FengxianFragment1;
import com.yogee.topseller.fragment.zhoubian.JigouFragment;
import com.yogee.topseller.fragment.zhoubian.FengxianFragment;
import com.yogee.topseller.fragment.zhoubian.ZixunFragment;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.LogUtils;
import com.yogee.topseller.utils.TabLayoutUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 数据周边
 * Created by Administrator on 2018/5/14.
 */

public class ZhoubianActivity extends HttpActivity {

//    @BindView(R.id.layout_title_back_iv)
//    ImageView layout_title_back_iv;.
    @BindView(R.id.ll_rong)
    LinearLayout ll_rong;
    @BindView(R.id.ll_bao)
    LinearLayout ll_bao;
    @BindView(R.id.ll_fa)
    LinearLayout ll_fa;
    @BindView(R.id.view_line1)
    View view_line1;
    @BindView(R.id.view_line2)
    View view_line2;
    @BindView(R.id.view_line3)
    View view_line3;
    @BindView(R.id.rv_jg)
    RecyclerView rv_jg;

    private List<JigouBean.Company> companyList=null;
    private JigouAdapter jigouAdapter;

    //Fragment的数据集合
    List<Fragment> fragmentList1 = null;
    //标题数据集合
    List<String> titles1 = null;

    //Fragment的数据集合
    List<Fragment> fragmentList2 = null;
    //标题数据集合
    List<String> titles2 = null;

    private String proId = "";
    // 0 融资 1担保 2发行
    private String type = "0";

    private Handler handler=null;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_zhoubian;
    }

    @Override
    protected void initView() {
        proId = getIntent().getStringExtra("proId");
        handler=new Handler();
        titles2 = new ArrayList<>();
        titles2.add("风险");
        titles2.add("资讯");
        titles2.add("产品");

        fragmentList2 = new ArrayList<>();
        FengxianFragment1 fengxianFragment = new FengxianFragment1();
        fragmentList2.add(fengxianFragment);
        ZixunFragment zixunFragment = new ZixunFragment();
        fragmentList2.add(zixunFragment);
        GongsiProFragment gongsiProFragment = new GongsiProFragment();
        fragmentList2.add(gongsiProFragment);
        new TabLayoutUtil(getSupportFragmentManager(), findViewById(R.id.ll_zhoubian), fragmentList2, titles2, 112);
        rv_jg.setLayoutManager(new LinearLayoutManager(this));
//        rv_jg.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false){
//            @Override
//            public boolean canScrollVertically() {
//                return false;
//            }
//        });
        jigouAdapter = new JigouAdapter(this,rv_jg);
        rv_jg.setAdapter(jigouAdapter);
        initData(type);

//        titles1 = new ArrayList<>();
//        titles1.add("融资方");
//        titles1.add("担保方");
//        titles1.add("发行方");
//        fragmentList1 = new ArrayList<>();

//        for(int i = 0;i<3;i++){
//            JigouFragment jigouFragment1 = new JigouFragment();
//            Bundle bundle = new Bundle();
//            bundle.putInt("isMj", i);
//            bundle.putString("proId",proId);
//            jigouFragment1.setArguments(bundle);
//            fragmentList1.add(jigouFragment1);
//        }
//        new TabLayoutUtil(getSupportFragmentManager(), findViewById(R.id.ll_zhoubian), fragmentList1, titles1, 111);


    }

    /**
     * 数据初始化
     */
    private void initData(String type){
        HttpManager.getInstance().relatedCompanyTypeDetails(proId,type).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<JigouBean>() {
            @Override
            public void onNext(JigouBean o) {
                List<JigouBean.Company> list = o.getMechanismList();

                if(list!=null&&list.size()>0)
                    jigouAdapter.addData(o.getMechanismList());
                else{
                    jigouAdapter.addData(null);
                    ToastUtils.showToast(ZhoubianActivity.this,"暂无机构");
//                    ZhoubianActivity.this.finish();
                }

            }
        }, this));
    }
    @OnClick({R.id.ll_rong,R.id.ll_bao,R.id.ll_fa,R.id.layout_title_back_iv})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.ll_rong:
                type = "0";
                initData("0");
                view_line1.setVisibility(View.VISIBLE);
                view_line2.setVisibility(View.INVISIBLE);
                view_line3.setVisibility(View.INVISIBLE);
                ll_rong.setBackgroundResource(R.color.white);
                ll_bao.setBackgroundResource(R.color.colorAllBG);
                ll_fa.setBackgroundResource(R.color.colorAllBG);
                break;
            case R.id.ll_bao:
                type = "1";
                initData("1");
                view_line1.setVisibility(View.INVISIBLE);
                view_line2.setVisibility(View.VISIBLE);
                view_line3.setVisibility(View.INVISIBLE);
                ll_rong.setBackgroundResource(R.color.colorAllBG);
                ll_bao.setBackgroundResource(R.color.white);
                ll_fa.setBackgroundResource(R.color.colorAllBG);
                break;
            case R.id.ll_fa:
                type ="2";
                initData("2");
                view_line1.setVisibility(View.INVISIBLE);
                view_line2.setVisibility(View.INVISIBLE);
                view_line3.setVisibility(View.VISIBLE);
                ll_rong.setBackgroundResource(R.color.colorAllBG);
                ll_bao.setBackgroundResource(R.color.colorAllBG);
                ll_fa.setBackgroundResource(R.color.white);
                break;
            case R.id.layout_title_back_iv:
                ZhoubianActivity.this.finish();
                break;
        }
    }

    UpdateListener updateListener1,updateListener2,updateListener3;
    public interface UpdateListener{
        public void getCurrentPos(JigouBean.Company company);
    }
    public void setListener1(UpdateListener listener){
        this.updateListener1 = listener;
    }
    public void setListener2(UpdateListener listener){
        this.updateListener2 = listener;
    }
    public void setListener3(UpdateListener listener){
        this.updateListener3 = listener;
    }

    private JigouBean.Company mySelectCompany= new JigouBean.Company();
    public void setCurrentPosInfo(JigouBean.Company company){
        mySelectCompany = company;
        if(company!=null){
            mySelectCompany.setProId(proId);
            mySelectCompany.setType(type);

        }else{
            LogUtils.e("选择机构为空","0000");
        }

        if(updateListener1!=null)
            updateListener1.getCurrentPos(company);
        if(updateListener2!=null)
            updateListener2.getCurrentPos(company);
        if(updateListener3!=null)
            updateListener3.getCurrentPos(company);
    }

    public JigouBean.Company getMySelectCompany(){
        if(mySelectCompany!=null)
            mySelectCompany.setProId(proId);
        return mySelectCompany;
    }
    public String getType(){
        return type;
    }
    public String getProId(){
        return proId;
    }







    // 构建Runnable对象，在runnable中更新界面
    Runnable   runnableUi=new  Runnable(){
        @Override
        public void run() {
            if (pd != null) {
                pd.dismiss();
            }
            ToastUtils.showToast(ZhoubianActivity.this, "无数据");
        }

    };

    public void getId(String name) {
        if (!NetUtil.isNetworkAvailable()) {
            ToastUtils.showToast(ZhoubianActivity.this, "网络中断了，请重新链接网络。");
            return;
        }
        if (pd != null) {
            pd.show();
        }
        if(!AppUtil.isFastDoubleClick()){
            if (pd != null) {
                pd.dismiss();
            }
            return;
        }

        //组装调取银行卡验证api的数据
        JSONObject object = new JSONObject();
        try {
            object.put("name", name);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //网络调取api
//        OkHttpClient okHttpClient = new OkHttpClient();

        OkHttpClient okHttpClient =
                new OkHttpClient.Builder()
                        .readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间
                        .writeTimeout(60, TimeUnit.SECONDS)//设置写的超时时间
                        .connectTimeout(60, TimeUnit.SECONDS)//设置连接超时时间
                        .build();
        Request.Builder builder = new Request.Builder();

        Request request = builder.get()
                .url("http://open.api.tianyancha.com/services/v4/open/baseinfo?name=" + name)  //fxjg
                .addHeader("Authorization", "09d5ca00-9913-4490-bba2-eedf81599fbf")
//                .addHeader("Content-Type", "application/json; charset=UTF-8")
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, final IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (pd != null) {
                            pd.dismiss();
                        }
                        handler.post(runnableUi);
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {

                            Gson gson = new Gson();
                            String result = response.body().string().replace("\n", "");
                            LogUtils.e("success", result);
                            JSONObject jsonObject = new JSONObject(result);
                            int error_code = jsonObject.getInt("error_code");
                            if (error_code != 0) {
                                handler.post(runnableUi);
                            } else {
                                if (pd != null) {
                                    pd.dismiss();
                                }
                                long id = jsonObject.getJSONObject("result").getLong("id");
                                LogUtils.e("id", "id:" + id);
                                startActivity(new Intent().setClass(ZhoubianActivity.this, HyqxActivity1.class).putExtra("fxjg", id+""));
                            }
                        } catch (Exception e) {
                            handler.post(runnableUi);
                        }
                    }
                }).start();
            }
        });
    }
}
